package com.jyxd.web.config;

import com.alibaba.druid.filter.logging.Slf4jLogFilter;
import com.alibaba.druid.filter.stat.StatFilter;
import com.alibaba.druid.pool.DruidDataSource;
import com.google.common.collect.Lists;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.sql.SQLException;

@Configuration
public class DruidConfig {

    @Bean
    public Slf4jLogFilter logFilter(){
        Slf4jLogFilter logFilter = new Slf4jLogFilter();
        logFilter.setConnectionLogEnabled(true);
        logFilter.setResultSetLogEnabled(true);
        logFilter.setStatementLogEnabled(true);
        logFilter.setStatementExecutableSqlLogEnable(true);
        return logFilter;
    }
    @Bean
    public StatFilter statFilter () {
        StatFilter statFilter = new StatFilter();
        statFilter.setSlowSqlMillis(3000);
        statFilter.setLogSlowSql(true);
        statFilter.setMergeSql(true);
        return statFilter;
    }

    public static void initDataSource(DruidDataSource dataSource,Slf4jLogFilter slf4jLogFilter,StatFilter statFilter) throws SQLException {
        dataSource.setMinIdle(5);
        dataSource.setInitialSize(5);
        dataSource.setMaxActive(20);
        dataSource.setTimeBetweenEvictionRunsMillis(60000);
        dataSource.setMinEvictableIdleTimeMillis(300000);
        dataSource.setMaxEvictableIdleTimeMillis(400000);
        dataSource.setValidationQuery("SELECT 1");
        dataSource.setTestWhileIdle(true);
        dataSource.setTestOnBorrow(false);
        dataSource.setTestOnReturn(false);
        dataSource.setProxyFilters(Lists.newArrayList(slf4jLogFilter,statFilter));
    }
}
